package com.yummiii.dokueditor.controller;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

import com.yummiii.dokueditor.model.doku.DokuNamespace;
import com.yummiii.dokueditor.model.doku.DokuPage;
import com.yummiii.dokueditor.model.page.Document;

public class DokuController {
	PrefController prefController;
	static String dokuURL;

	public DokuController(PrefController prefController) {
		this.prefController = prefController;
		dokuURL = prefController.getURL() + "?u="
				+ prefController.getUsername() + "&p="
				+ prefController.getPassword();
	}

	public DokuNamespace getPagelist(String father) throws MalformedURLException, XmlRpcException {
		Object[] pageList=(Object[]) excuteRemoteAPI("dokuwiki.getPagelist",new Object[]{father,""});
		DokuNamespace root=new DokuNamespace("");
		for(Object page:pageList){
			HashMap<String,Object> p=(HashMap<String, Object>) page;
			String id=(String) p.get("id");
			int mtime=(Integer)p.get("mtime");
			int size=(Integer)p.get("size");
			String[] path=id.split(":");
			DokuNamespace currentNS=root;
			for(int i=0;i<path.length;i++){
				if(i<path.length-1){
					if(!currentNS.hasNamespace(path[i]))
						currentNS=currentNS.addNamespace(path[i]);
					else
						currentNS=currentNS.getNamespace(path[i]);
				}
				else{
					if(!currentNS.hasPage(path[i]))
						currentNS.addPage(path[i], mtime, size);
				}
			}
		}
		return root;
	}

	public String getPage(DokuPage page) throws MalformedURLException, XmlRpcException {
		Object recPage=excuteRemoteAPI("wiki.getPage", new Object[]{page.getFullName()});
		String pageContent=(String) recPage;
		return pageContent;
	}

	HashMap<String, Object>[] getPageInfo(DokuPage page) {
		return null;
	}

	boolean putPage(Document document) {
		return false;
	}

	Object excuteRemoteAPI(String methodName, Object[] para)
			throws MalformedURLException, XmlRpcException {
		XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
		config.setServerURL(new URL(dokuURL));
		
		XmlRpcClient client = new XmlRpcClient();
		client.setConfig(config);

		Object result = client.execute(methodName, para);
		return result;

	}

	boolean testRemoteAPI() {
		return false;
	}
}
